<template>
  <div class="pagss">


    <el-dialog center title="沟通" :visible.sync="open" width="42%" append-to-body @open="scrollToBottom" :close-on-click-modal="false">


      <div class="dialog-content">
        <div class="dialog-scroll" ref="scrollableContainer">
          <!-- 内容 -->


          <div v-for="item in List" :key="item.value" :value="item.value" class="mr20">

            <div class="row_a_c">
              <div class="xyd mr_18"></div>
              <div class="f_14">{{item.created_at}}</div>
            </div>

            <div class="one" :class="{toone:item.type==2}">
              <div class="f_16">{{item.content}}</div>
              <div class="mt_16" v-if="item.type==1"><span class="f_bold">{{item.sender.nickname}}</span> 提交于
                {{item.created_at}}
              </div>
              <div class="mt_16" v-else><span class="f_bold">{{item.sender.nickname}}</span> 回复于 {{item.created_at}}</div>

              <div class="row_a_c mt20">
                <div v-for="(item_sc,index) in item.screenshot" :key="index" class="mr10">
                  <el-image style="width: 100px; height: 100px" :src="item_sc" :preview-src-list="item.screenshot"></el-image>
                </div>
              </div>

              <div class="mt_16">
                <div v-for="(item_att,indexatt) in item.attachment" :key="indexatt+'a'" class="mb5">
                  <a :href="item_att">文件{{indexatt+1}}</a>
                </div>
              </div>
              
            </div>


          </div>

          <el-form ref="form" :model="form" :rules="rules" label-width="100px" label-position="left" class="mr_20">

            <el-form-item label="反馈更多信息" prop="content" align="right">
              <el-input type="textarea" v-model="form.content" placeholder="请输入" :autosize="{ minRows: 4, maxRows: 6}" />
            </el-form-item>


            <el-form-item label="问题截图">
              <el-upload :action="upload_url" :headers="headers" list-type="picture-card" :on-success="handleChangePho" :file-list="phoFiles" :on-remove="handleRemovePho" :show-file-list="true">
                <i class="el-icon-plus"></i>
              </el-upload>
            </el-form-item>

            <el-form-item label="附件">
              <el-upload class="upload-demo" :action="upload_url" :on-remove="handleRemove" :on-change="handleChange" :file-list="fileList">
                <el-button size="small" type="primary">点击上传</el-button>
              </el-upload>
            </el-form-item>

          </el-form>

          <div slot="footer" class="dialog-footer center">

            <div class="quxiao">
              <el-button style="width: 200px;height: 40px;margin-right: 30px;" @click="cancelGt">取消</el-button>
            </div>
            <el-button style="width: 200px;height: 40px;" ref="sendButton" type="primary" @click="submitForm">发送(Ctrl+Enter)</el-button>
          </div>

        </div>
      </div>
    </el-dialog>


  </div>
</template>

<script>
  import * as Work from "@/api/operation/work";
  import MD5 from 'md5';
  import * as Auth from '@/utils/auth';
  export default {
    name: 'Index',
    components: {

    },
    data() {
      return {


        title: '',
        ulid: '',
        userId: '',
        nickname: '',
        List: [], //问题列表
        upload_url: process.env.VUE_APP_BASE_URL + '/file/upload',
        upload_url_all: process.env.VUE_APP_BASE_URL + '/file/uploadAll',
        headers: Auth.getHeader(),
        form: {},
        open: false,

        // fileList: [],
        fileList: [],


        loading: false,
        phoFiles: [],
        currentPage4: 1, //当前页
        time_value: '',
        imageUrl: '',
        // 查询参数
        queryParams: {
          noPage: 1,
          pageSize: 10
        },
        ruleForm: {
          business_type: '',
          name: '',
          account_number: '',
          work_number: '',
          handling_person: '',
          form_state: '',
        },


        // 表单校验
        rules: {
          title: [{
            required: true,
            message: "问题标题不能为空",
            trigger: "blur"
          }],
          type: [{
            required: true,
            message: '请选择问题分类',
            trigger: 'change'
          }],
          detail: [{
            required: true,
            message: '问题详情描述不能为空',
            trigger: 'change'
          }],
        },



      }
    },
    created() {
      // 读取缓存
      this.nickname = localStorage.getItem('username')
      this.userId = localStorage.getItem('user_id')
      localStorage.setItem('message_show', 0)

      //获取工单消息列表
      // this.getWorkMessageList();
    },
    mounted() {
      // 获取按钮元素的引用
      const sendButton = this.$refs.sendButton;

      // 添加键盘事件监听器
      document.addEventListener('keydown', (event) => {
        // 按下 Ctrl+Enter 组合键时触发发送操作
        if (event.ctrlKey && event.key === 'Enter') {
          // 阻止默认的 Enter 键行为，以免触发表单提交等操作
          // event.preventDefault();

          // 执行发送操作
          this.submitForm();
        }
      });
    },
    methods: {

      scrollToBottom() {

        setTimeout(() => {
          this.$nextTick(() => {
            if (this.$refs.scrollableContainer) {
              const scrollableContainer = this.$refs.scrollableContainer;
              scrollableContainer.scrollTop = scrollableContainer.scrollHeight;
            }

          });
        }, 200);

      },

      // 表单重置
      reset() {
        this.fileList = [];
        this.phoFiles = [];
        this.form = {};
        this.resetForm("form");
      },


      childMethod(row) {
        this.ulid = row.ulid;
        this.user = row.user;
        this.open = true;
        this.getWorkMessageList(); //获取工单消息列表
      },


      childWebSocket(data) {
        this.List.push(data);
        localStorage.setItem('message_show', 0)
        this.scrollToBottom();
      },


      //获取工单消息列表
      getWorkMessageList() {
        localStorage.setItem('message_show', 0)
        this.loading = true;
        var peres = {}
        peres.workOrder = this.ulid;
        peres.type_pj = 1
        // var per = this.splicingParameter(peres);

        Work.getWorkMessageList(peres).then((response) => {

          this.List = response.data.list
          console.log('aaa', response.data.list)
          this.loading = false;
        });
      },

      getCurrentDateTime() {
        const currentDate = new Date();
        const year = currentDate.getFullYear();
        const month = String(currentDate.getMonth() + 1).padStart(2, '0');
        const day = String(currentDate.getDate()).padStart(2, '0');
        const hours = String(currentDate.getHours()).padStart(2, '0');
        const minutes = String(currentDate.getMinutes()).padStart(2, '0');
        const seconds = String(currentDate.getSeconds()).padStart(2, '0');
        var currentDateTime = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
        return currentDateTime;
      },



      /** 提交按钮 */
      submitForm: function() {
        this.$refs['form'].validate(valid => {
          if (valid) {

            this.form.workOrder = this.ulid
            this.form.user = this.userId
            this.form.organization = this.userId
            this.form.type_pj = 1
            this.form.content = this.form.content.trim()
            var _this = this
            Work.Gdfk(this.form).then(response => {
              this.$modal.msgSuccess('新增成功');
              var data = {
                sender: {
                  nickname: ''
                }
              }
              data.content = _this.form.content
              data.attachment = _this.form.attachment
              data.screenshot = _this.form.screenshot
              data.sender.nickname = '我'
              data.type = 1

              data.created_at = this.getCurrentDateTime()
              _this.List.push(data);
              localStorage.setItem('message_show', 0)
              // this.open = false;
              // this.getList();
            });

          }
        });
      },



      // 设置photo值--图片上传拼接数据
      phoChange(fileList) {
        let temp_str = '';
        if (fileList.length > 0) {
          for (let i = 0; i < fileList.length; i++) {
            if (fileList[i].response) {
              if (fileList[i].response.code === 200) {
                if (i === 0) {
                  temp_str += fileList[i].response.data;
                } else {
                  // 最终photo的格式是所有已上传的图片的url拼接的字符串（逗号隔开）

                  temp_str += ',' + fileList[i].response.data;
                }
              }
            }
          }
        }

        this.form.screenshot = temp_str.split(',');
      },


      // 设置file值--文件上传拼接数据
      fileChange(fileList) {
        let temp_str = '';
        if (fileList.length > 0) {
          for (let i = 0; i < fileList.length; i++) {
            if (fileList[i].response) {
              if (fileList[i].response.code === 200) {
                if (i === 0) {
                  temp_str += fileList[i].response.data;
                } else {
                  // 最终photo的格式是所有已上传的图片的url拼接的字符串（逗号隔开）

                  temp_str += ',' + fileList[i].response.data;
                }
              }
            }
          }
        }

        this.form.attachment = temp_str.split(',');
      },

      //相册上传成功调用
      handleChangePho(res, file, fileList) {
        this.phoChange(fileList);
      },

      //文件上传成功调用
      handleChange(file, fileList) {
        this.fileChange(fileList);
      },

      // 取消按钮
      cancel() {
        this.open = false;
      },

      // 沟通取消按钮
      cancelGt() {
        this.open = false;
      },
      //图片移出
      handleRemovePho(file, fileList) {
        this.phoChange(fileList);
        console.log('file', file);
        console.log('fileList', fileList);
      },

      //文件移出
      handleRemove(file, fileList) {
        this.fileChange(fileList);
      },
    }
  }
</script>

<style lang="scss" scoped>
  .xyd {
    width: 12px;
    height: 12px;
    background: #DFE4ED;
    border: 1px solid #3C89FF;
    border-radius: 50%;
  }

  .one {
    margin-left: 30px;
    margin-top: 20px;
    margin-bottom: 30px;
    padding: 30px;
    min-height: 123px;
    background: #FFFFFF;
    box-shadow: 0px 2px 8px 0px rgba(26, 76, 176, 0.45);
    border-radius: 4px;
  }

  .toone {
    background: #3C89FF !important;
    color: #FFFFFF !important;
  }

  .dialog-content {
    height: 800px;
    /* 设置对话框内容容器的固定高度 */
    position: relative;
    /* 设置相对定位，以便在滚动时保持对话框位置固定 */
    overflow: hidden;
    /* 隐藏溢出内容 */
  }

  .dialog-scroll {
    height: 100%;
    /* 设置滚动容器的高度为内容容器的高度 */
    overflow-y: auto;





    /* 添加垂直滚动条 */
  }
</style>
